package com.example.demo.juc;

import java.util.concurrent.Semaphore;

/**
 * ClassName: Semaphore
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/07/31-23:23:00
 * Description:
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        /**
         * 三个停车位
         */
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    System.out.println("当前：" + Thread.currentThread().getName() + "车找停车位");
                    semaphore.acquire();
                    System.out.println("当前：" + Thread.currentThread().getName() + "车进入停车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("当前：" + Thread.currentThread().getName() + "车离开停车位");
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
